package com.example.calcite.xml;

import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlSelect;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql.util.SqlBasicVisitor;

public class XmlSqlParser {
    public static String extractXmlId(String sql) {
        try {
            SqlParser parser = SqlParser.create(sql);
            SqlNode sqlNode = parser.parseQuery();
            return new XmlIdExtractor().visit((SqlCall) sqlNode);
        } catch (Exception e) {
            throw new RuntimeException("Error parsing SQL", e);
        }
    }

    private static class XmlIdExtractor extends SqlBasicVisitor<String> {
        @Override
        public String visit(SqlCall call) {
            if (call instanceof SqlSelect) {
                SqlSelect select = (SqlSelect) call;
                SqlNode from = select.getFrom();
                if (from instanceof SqlIdentifier) {
                    SqlIdentifier identifier = (SqlIdentifier) from;
                    if (identifier.names.size() >= 2 &&
                            identifier.names.get(0).equalsIgnoreCase("XML")) {
                        return identifier.names.get(1);
                    }
                }
            }
            return null;
        }
    }
}